package com.hzit.filter;


import cn.hutool.http.server.HttpServerRequest;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//1. 得到session对象,判断是否有username属性，如果有，证明登录过
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		//2. 得到当前请求地址
		String uri = req.getRequestURI();
		//3. 得到查询字符串（请求地址中？后的内容）
		String queryString = req.getQueryString();
		//4. 拼凑查询字符串
		String queryInfo =  uri + "?" +  queryString;

		HttpSession session = req.getSession();
		Object username = session.getAttribute("username");
		// if(username != null || "/login.jsp".equals(uri)){  // 此时放行
		// 	chain.doFilter(request,response);
		// }else if("/user?cmd=login".equals(queryInfo)){  // 证明现在是登录处理页面，要放行
		// 	chain.doFilter(request,response);
		// }
		//几个判断条件的说明：
		// username!= null: 代表登录过
		// "/login.jsp".equals(uri): 代表当前访问的是login.jsp这个登录页面
		// "/user?cmd=login".equals(queryInfo): 代表登录表单的处理页面
		if(username != null || "/login.jsp".equals(uri) || "/user?cmd=login".equals(queryInfo)){
			chain.doFilter(request,response);
		}
		else{                  // 没有登录就跳转回登录页面
			req.setAttribute("msg","请登录！");
			req.getRequestDispatcher("/login.jsp").forward(request,response);
		}
	}

	// http://localhost:9000/student?cmd=list
	// login.jsp--->submit()--->/user?cmd=login
	@Override
	public void destroy() {

	}
}
